package com.peng.leetcode.heap;

import java.util.Arrays;
import java.util.Comparator;

/**
 * EraseOverlapIntervals
 *
 * @author: lupeng6
 * @create: 2020/12/31 17:47
 */
public class EraseOverlapIntervals {

    public static void main(String[] args) {
//        int[][] intervals = {{1, 2}, {2, 3}, {3, 4}, {1, 3}};
//        int[][] intervals = {{1,100},{11,22},{1,11},{2,12}};
//        int[][] intervals = {{1, 2}, {1, 2}, {1, 2}};
        int[][] intervals = {{0, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}};
        System.out.println(eraseOverlapIntervals(intervals));
    }

    public static int eraseOverlapIntervals(int[][] intervals) {
        if (intervals == null || intervals.length <= 1) {
            return 0;
        }
        int count = 0;
        Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
        int[] prev = intervals[0];
        for (int i = 1; i < intervals.length; i++) {
            int[] interval = intervals[i];
            if (prev[1] > interval[0]) {
                // 相交 取区间最小的
                count++;
                if (prev[1] > interval[1]) {
                    prev = interval;
                }
            } else {
                // 不想交, 替换上一个
                prev = interval;
            }
        }
        return count;
    }
}
